package org.benjamin.lending.security;

import java.io.IOException;
import java.sql.Timestamp;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.benjamin.lending.domain.entity.LoginLog;
import org.benjamin.lending.domain.entity.LoginLog.LoginMethon;
import org.benjamin.lending.repository.LoginLogRepository;
import org.benjamin.lending.domain.entity.MemberInfo;
import org.benjamin.lending.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler{
	
	@Autowired
	private MemberService memberService;
	
	@Autowired
	private LoginLogRepository loginLogRepository;
	
	private final Logger logger= LogManager.getLogger();

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		logger.info("Success Handler");
		String username = authentication.getName();
		MemberInfo memberInfo = this.memberService.userLogin(username);
		String loginAddress = request.getRemoteAddr();
		LoginLog loginLog = new LoginLog();
		loginLog.setLoginAddress(loginAddress);
		loginLog.setMemberInfo(memberInfo);
		loginLog.setLoginMethon(LoginMethon.WEB);
		loginLog.setLoginTime(new Timestamp(System.currentTimeMillis()));
		this.loginLogRepository.save(loginLog);
		super.onAuthenticationSuccess(request, response, authentication);
	}

	
}
